package cn.ihna.demo.client.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author xianyingda@gmail.com
 * @serial
 * @since 2020-08-15 00:58
 */
public class NettyClient {

    private String host;
    private int port;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        // 线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 客户端启动必备
            Bootstrap b = new Bootstrap();
            b.group(group) // 传入线程组
                    .channel(NioSocketChannel.class) // 指定使用nio进行网络通信
                    .remoteAddress(new InetSocketAddress(host, port)) // 指定远程服务器
                    .handler(new EchoClientHandler())
            ;
            // 连接到远程节点 阻塞直到连接完成
            ChannelFuture f = b.connect().sync();

            // 阻塞close事件 防止程序退出
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new NettyClient("127.0.0.1", 10010).start();
    }
}
